﻿using HeyPiPi_Desk.Domain;
using HeyPiPi_Desk.Models;
using Microsoft.Practices.Prism.ViewModel;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Practices.Prism.Commands;
using System.Windows;
using HeyPiPi_Desk.Tools;
using System.Windows.Controls;
using HeyPiPi_Desk.Base;
using IDeskServiceBLL;
using DeskInterfaceBLL;
using Model;
using CustomModel;
using Utility;
using System.IO;
using LibrarySystem.Tools;
using System.Threading;
using MaterialDesignThemes.Wpf;

namespace HeyPiPi_Desk.ViewModels
{
    public  class MainWindowViewModel: BaseNotification
    {


        #region 字段/属性


        public TreeView TreeView { get; set; }

        private readonly IShopBLL shopBLL = new ShopBLL();

        private string currentItemName = "主页";

        /// <summary>
        /// 树形图选择命令
        /// </summary>
        public DelegateCommand<object> TreeItemSelectCmd { get; set; }

        /// <summary>
        /// 窗体移动事件
        /// </summary>
        public DelegateCommand<object> Move_Cmd { get; set; }

        private ObservableCollection<MainMenuModel> _mainMenu;

        /// <summary>
        /// 撤销反撤销 命令
        /// </summary>
        public DelegateCommand<object> History_Cmd { get; set; }

        private UserControl _uiContent;

        private bool _toggleDisplay;

        /// <summary>
        /// 菜单栏是否打开
        /// </summary>
        public bool ToggleDisplay
        {
            get { return _toggleDisplay; }
            set { _toggleDisplay = value;this.RaisePropertyChanged(() => this.ToggleDisplay); }
        }


        /// <summary>
        /// 存放当前面板的容器
        /// </summary>
        public UserControl UiContent
        {
            get { return _uiContent; }
            set { _uiContent = value; this.RaisePropertyChanged(() => this.UiContent); }
        }

        private string _title;

        /// <summary>
        /// 显示标题
        /// </summary>
        public string Title
        {
            get { return _title; }
            set { _title = value; this.RaisePropertyChanged(() => this.Title); }
        }


        private string _minMaxIcon= "WindowMaximize";
        /// <summary>
        /// 最大化最小化图标字符串
        /// </summary>
        public string MinMaxIcon
        {
            get { return _minMaxIcon; }
            set { _minMaxIcon = value;this.RaisePropertyChanged(() => this.MinMaxIcon); }
        }

        /// <summary>
        /// 最大化最小化命令
        /// </summary>
        public DelegateCommand<object> MinMax_Cmd { get; set; }

        /// <summary>
        /// 最小化命令
        /// </summary>
        public DelegateCommand<object> Min_Cmd { get; set; }

        public ObservableCollection<MainMenuModel> MainMenu
        {
            get { return _mainMenu; }
            set { _mainMenu = value; this.RaisePropertyChanged(()=>this.MainMenu); }
        }

        /// <summary>
        /// 鼠标进入菜单标头打开菜单
        /// </summary>
        public DelegateCommand MouseEnterOpenMenu_Cmd { get; set; }

        /// <summary>
        /// 清除面板历史
        /// </summary>
        public DelegateCommand ClearHistory { get; set; }

        #endregion

        public MainWindowViewModel()
        {
            //   this._init();

            // 本地化文件
            this._processFile();

            // 获得用户权限
            List<string> priv_list = new List<string>(); //todo 模拟权限。调用接口
            this.MainMenu = CreateMenu.GetInstance().GetMenuList(priv_list);
            //初始化显示主页面
            this.UiContent = DomainResponsitory.GetInstance().GetDomain("主页",DomainStatus.newdomain);

            // 绑定事件
            this._commandSets();

        }

        /// <summary>
        /// 处理本地文件
        /// </summary>
        private void _processFile()
        {
            //判断是否生成用户文件，
            if (XmlHelper.XmlExist(GlobalPath.GetCustomConfigPath()+GlobalParam.user+".xml"))
            {
                // 读取本地配置
           
            }
            else
            {
                // 判断路径是否存在
                if (!Directory.Exists(GlobalPath.GetCustomConfigPath()))
                {
                    Directory.CreateDirectory(GlobalPath.GetCustomConfigPath());
                }

                XmlHelper.CreateXml(GlobalPath.GetCustomConfigPath() + GlobalParam.user + ".xml");
                if (XmlHelper.XmlExist(GlobalPath.GetCustomConfigPath()+GlobalParam.user+".xml"))
                {
                    // reader local config
                }
                else
                {
                     

                    MessageBox.Show("创建本地配置失败，可能是权限原因，请重新安装软件(不要安装到C盘)","错误",MessageBoxButton.OK,MessageBoxImage.Error);
                    Application.Current.MainWindow.Close();

                }

            }


        }

        /// <summary>
        /// 注册绑定事件
        /// </summary>
        private void _commandSets()
        {
            this.ClearHistory = new DelegateCommand(() =>
            {
                if( DomainResponsitory.GetInstance().ClearHistory())
                {
                    GlobalSetting.GetGlobalSetting().OpenTipMessage("删除历史成功");
                }
                else
                {
                    GlobalSetting.GetGlobalSetting().OpenTipMessage("删除历史失败");
                }
            });

            this.MouseEnterOpenMenu_Cmd = new DelegateCommand(() =>
            {
                bool isopen = Convert.ToBoolean(GlobalSetting.GetGlobalSetting().GetSetting(SettingParamEnum.MouseEnterOpenMenu));
                if (isopen==true)
                {
                    this.ToggleDisplay = true;
                }
                else
                {
                    this.ToggleDisplay = false;
                }

            });
            DomainResponsitory.GetInstance().TogglePanelEvent += (name,type) =>
            {
                foreach (var item in this.TreeView.Items)
                {
                    TreeViewItem parent = TreeView.ItemContainerGenerator.ContainerFromItem(item) as TreeViewItem;
                    foreach (var son in parent.Items)
                    {
                        if (son is ChildMenu core)
                        {
                            if(core.Name == name)
                            {
                                parent.IsExpanded = true;
                                TreeViewItem treeitem = parent.ItemContainerGenerator.ContainerFromItem(son) as TreeViewItem;
                                treeitem.IsExpanded = true;
                                treeitem.IsSelected = true;
                                this.currentItemName = name;
                            }
                          
                        }

                        
                    }

                   
                }

                //this.UiContent = DomainResponsitory.GetInstance().GetDomain(name, DomainStatus.newdomain);
                
            };

            this.MinMax_Cmd = new DelegateCommand<object>((obj) =>
            {
                Window window = obj as Window;
                if (this.MinMaxIcon== "WindowMaximize")
                {
                    window.WindowState = WindowState.Normal;
                    this.MinMaxIcon = "ImageFilterNone";
                }
                else
                {
                    window.WindowState = WindowState.Maximized;
                    this.MinMaxIcon = "WindowMaximize";
                }
            });
            this.Min_Cmd = new DelegateCommand<object>((obj) =>
            {
                Window window = obj as Window;
                window.WindowState = WindowState.Minimized;

            });
            this.Move_Cmd = new DelegateCommand<object>((obj) =>
            {
                Window window = obj as Window;
                window.DragMove();

            });

            this.TreeItemSelectCmd = new DelegateCommand<object>(obj =>
            {
                if (obj is ChildMenu item)
                {
                    DomainOpenMethod domainOpenMethod = DomainResponsitory.GetInstance().OpenMethod;
                    UserControl panel = null;
                    if (domainOpenMethod==DomainOpenMethod.HistoryOpen)
                    {
                        if (Convert.ToBoolean( GlobalSetting.GetGlobalSetting().GetSetting(SettingParamEnum.StackItemNewPanel)))
                        {
                            panel = DomainResponsitory.GetInstance().GetDomain(item.Name, DomainStatus.newdomain);
                        }
                        else
                        {
                            panel = DomainResponsitory.GetInstance().GetDomain(item.Name, DomainStatus.keepdomain);
                        }
                    }
                    else if (domainOpenMethod == DomainOpenMethod.PageOpen)
                    {
                        if (Convert.ToBoolean(GlobalSetting.GetGlobalSetting().GetSetting(SettingParamEnum.PageOpenNewPanel)))
                        {
                            panel = DomainResponsitory.GetInstance().GetDomain(item.Name, DomainStatus.newdomain);
                        }
                        else
                        {
                            panel = DomainResponsitory.GetInstance().GetDomain(item.Name, DomainStatus.keepdomain);
                        }
                    }
                    else if (domainOpenMethod == DomainOpenMethod.TreeOpen)
                    {
                        if (Convert.ToBoolean(GlobalSetting.GetGlobalSetting().GetSetting(SettingParamEnum.TreeOpenNewPanel)))
                        {
                            panel = DomainResponsitory.GetInstance().GetDomain(item.Name, DomainStatus.newdomain);
                        }
                        else
                        {
                            panel = DomainResponsitory.GetInstance().GetDomain(item.Name, DomainStatus.keepdomain);
                        }
                    }

                    if (panel != null)
                    {
                        this.ToggleDisplay = false;
                        this.Title = item.Name;
                        this.UiContent = panel;
                        this.currentItemName = item.Name;
                        //压入栈中
                        DomainResponsitory.GetInstance().PushItemInStack(item.Name);

                    }
                    DomainResponsitory.GetInstance().OpenMethod = DomainOpenMethod.TreeOpen;
                }
                else if (obj is MainMenuModel mainitem)
                {
                    if (mainitem.Name == "主页")
                    {
                        this.ToggleDisplay = false;
                        this.Title = mainitem.Name;
                        this.currentItemName = mainitem.Name;
                        this.UiContent = DomainResponsitory.GetInstance().GetDomain(mainitem.Name, DomainStatus.newdomain);
                    }
                }


            });

            this.History_Cmd = new DelegateCommand<object>((obj) =>
            {
                string type = obj.ToString();
                string name = null;
                if (type == "0") // 撤销
                {

                    do
                    {
                        name = DomainResponsitory.GetInstance().Redo();
                    } while (this.currentItemName==name);
                    

                }
                else
                {
                    do
                    {
                        name = DomainResponsitory.GetInstance().UnRedo();
                    } while (this.currentItemName==name);
                 
                }

                if (name!=null)
                {
               
                    DomainResponsitory.GetInstance().ChangedPanel(name, DomainOpenMethod.HistoryOpen);
                }
            
            });
        }

        private void _init()
        {

            //this._processFile();

            // 根据用户id获得当前的店铺
            List<shopinfo> shopinfos = this.shopBLL.GetShopInfos(GlobalParam.user.U_Id, ShopStatusEnum.正常,out this.error);

            if (ValidateError())
            {
                //多商铺处理
                if (shopinfos!=null&&shopinfos.Count>1)
                {
                    ChooseShopDialog chooseShopDialog = new ChooseShopDialog(shopinfos);
                    chooseShopDialog.DC.ChooseShopIdEvent += DC_ChooseShopIdEvent;
                }
                else // 当用户只有一个商铺
                {
                    GlobalParam.shop = shopinfos[0];

                }

            }

            // 在主页显示商铺主页的信息
            // 宠物预约服务
            // 待发货的商品
            //货源需要补充
            // 评价

        }

        /// <summary>
        /// 如果有多个店铺，被选择的id将会收到
        /// </summary>
        /// <param name="id">商户id</param>
        private void DC_ChooseShopIdEvent(shopinfo id)
        {
            GlobalParam.shop = id;
        }
    }
}
